package com.example.android.utils

import com.example.android.utils.livedata.LiveDataCallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit

private const val TAG = "RetrofitManager"


object NetUtil {
//    private var baseUrlDev: String = "http://10.22.199.170:8080"
//    private var baseUrlDev: String = "http://192.168.2.134:8080"
    private var baseUrlDev: String = "http://81.68.141.72:8080"
    private var baseUrl: String = "http://81.68.141.72:8082/topline/"
    private var timeoutDuration = 10L
    private val retrofitMap = ConcurrentHashMap<String, Retrofit>()
    private var okHttpBuilder = OkHttpClient.Builder()

    fun init(baseUrl: String) {
        this.baseUrl = baseUrl
    }

    fun getBaseUrlDev(): String {
        return baseUrlDev
    }

    fun getBaseUrl(): String {
        return baseUrl
    }

    fun setTimeoutDuration(timeoutDuration: Long) {
        this.timeoutDuration = timeoutDuration
    }

    fun get(baseUrl: String): Retrofit {
        var retrofit = retrofitMap[baseUrl]
        if (retrofit == null) {
            retrofit = createRetrofit(baseUrl)
            retrofitMap[baseUrl] = retrofit
        }
        return retrofit
    }

    fun get(): Retrofit {
        var retrofit = retrofitMap[baseUrl]
        if (retrofit == null) {
            retrofit = createRetrofit(baseUrl)
            retrofitMap[baseUrl] = retrofit
        }
        return retrofit
    }

    private fun createRetrofit(baseUrl: String): Retrofit {
        val myClient = okHttpBuilder
                .connectTimeout(timeoutDuration, TimeUnit.SECONDS)
                .addInterceptor(RequestInterceptor())
                .build()
        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(myClient)
                .addCallAdapterFactory(LiveDataCallAdapterFactory())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }

}